import java.util.ArrayList;
import java.util.List;

import drexel.db.DataAccess;
import drexel.db.DataAccess.MovieData;
import drexel.db.OracleDataAccess;
import drexel.loading.FileMovieLoader;
import drexel.loading.MovieLoader;
import drexel.marshalling.DOMXMLMarshaller;

public class Main {

    public static void main(String[] args) {

        if (args.length == 4) {

            MovieLoader loader = new FileMovieLoader("input");

            DataAccess dataAccess = new OracleDataAccess(args[0], args[1], args[2]);

            loadFiles(args[0], args[1], args[2], Integer.parseInt(args[3]));
            
            queryForResults(args[0], args[1], args[2]);

        } else {

            System.out.println("Usage: java -cp:. Main <db url> <user name> <password> <number of connections>");
        }
    }
    
    private static void loadFiles(String host, String userName, String password, int numberOfWorkers) {
    	
    	boolean beginLoading = false;
    	
    	List connections = new ArrayList();
    	
    	System.out.println("Establishing Database Connections ...");
    	
    	for (int i = 0; i < numberOfWorkers; i++) {
    		
    		DataAccess da = new OracleDataAccess(host, userName, password);
    		
    		if (da.open()) {
    			
    			connections.add(da);
    			
    		} else {
    			
    			System.out.println("ERROR: Unable to open data source. Unable to continue");
    			
    			break;
    		}
    		
    		if (i == (numberOfWorkers - 1)) {
    			
    			beginLoading = true;
    		}
    	}
    	
    	if (beginLoading) {
    		
	    	MovieLoader loader = new FileMovieLoader("input");
	    	
	    	loader.loadMovies(connections);
    	}
    	
    	for (int i = 0; i < connections.size(); i++) {
    	
    		DataAccess da = (DataAccess)connections.get(i);
    		
    		da.close();
    	}
    }
    
    private static void queryForResults(String host, String userName, String password) {
    	
        DataAccess dataAccess = new OracleDataAccess(host, userName, password);

        if (dataAccess.open()) {
        	
            MovieData forDirector = dataAccess.getAllMoviesAndGenresByDirector("Steven Spielberg");

            System.out.println("\nSearch All Movie Titles and Genres for Steven Spielberg an a Director\n");

            forDirector.print();

            MovieData forActor = dataAccess.getAllMoviesAndGenresByActor("Julia", "Roberts");

            System.out.println("\nSearch All Movie Titles and Genres for Julia Roberts as an Actor\n");

            forActor.print();

            dataAccess.close();
        }
    }
}
